import React, { Component } from 'react';
import ThePagination from "@/components/ThePagination";
import { Form, Input, Select, Space, Button, message, Tag, Modal, Row, Col, InputNumber } from "antd";
import { SearchOutlined, ExclamationCircleOutlined } from "@ant-design/icons";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import GoBack from '@/components/TheGoBack'
import { apiStockSupplierManageList, apiStockLibraryManageList } from '@/request/storageManager/store.js'
import { apiStockOutLibraryAdd, apiStockOutLibraryEdit, apiTSysDictionariesList, apiStockOutLibraryPrintDetail, apiStockOutLibraryView, apiStockOutLibraryConfirm, apiStockOutLibraryInfoAdd, apiStockOutLibraryInfoDel, apiStockOutLibraryInfoList } from '@/request/storageManager/outPut.js'
import { apiGetGoodsList, apiAdd, apiEdit, apiGetGoodsDetail, apiView } from '@/request/marketingTool'
import { exportSheetTable } from '@/utils/exportTable.js'
import { printLogo, toPrint } from '@/utils/toPrint'

import './style.scss'
import store from "@/store/store"
import OutPut from '..';
const { Search } = Input
const { Option } = Select
const { TextArea } = Input

export default class OutPutAdd extends Component {
    constructor() {
        super()
        this.FormRef = React.createRef()
        this.addFormRef = React.createRef()
        this.state = {
            searchDataSource: [],
            columns: [
                {
                    title: "序号",
                    dataIndex: "index",
                    key: "index",
                    render: (text, record, index) => {
                        return ((this.state.pageData.pageNo - 1) * (this.state.pageData.pageSize) + (index + 1));
                    }
                },
                {
                    title: "商品名称",
                    dataIndex: "goodsName",
                    key: "goodsName",

                },
                {
                    title:'物料名称',
                    dataIndex:'materialName',
                    key:'materialName'
                },
                {
                    title: "规格",
                    dataIndex: "skuName",
                    key: "skuName",

                },
                {
                    title: "物料ID",
                    dataIndex: "goodsSkuNo",
                    key: "goodsSkuNo",


                },
                {
                    title: "出库前库存",
                    dataIndex: "beforeCount",
                    key: "beforeCount",

                },
                {
                    title: "出库数量",
                    dataIndex: "count",
                    key: "count",

                },

                {
                    title: "操作时间",
                    dataIndex: "createTime",
                    key: "createTime",

                }, {
                    title: "操作人",
                    dataIndex: "createUserName",
                    key: "createUserName",
                }, {
                    title: "操作",
                    fixed: 'right',
                    render: (text, render, index) => {
                        return <div>

                            <TheButton haspermi={['storage:outPut:delInfo']} onClick={() => this.del(render, index)}>删除</TheButton>
                        </div>
                    }
                },
            ],
            dataSource: [],
            pageData: {
                pageNo: 1,
                pageSize: 10

            },
            total: 0,
            isModalVisible: false,
            loading: false,
            isSave: false,
            id: null,
            storeList: [],
            supplierList: [],
            code: '',
            libraryId: '',
            outLibraryId: '',
            productSku: [],
            currentSku: [],
            materialId: '',
            goodsList: [],
            options: [
                { name: '商城销售出库单', value: '0', disabled: true },
                { name: '门店销售出库单', value: '1', disabled: true },
                { name: '调拨出库单', value: '2', disabled: false },
                { name: '手动创建出库单', value: '3', disabled: false },
                { name: '发起砍价', value: '4', disabled: true },
                { name: '收银台出库单', value: '5', disabled: true }
            ],
            details: [],
            status: null,
            AllLibraryId: false
        }
    }
    componentDidMount() {
        this.setState({
            id: this.props.match.params.id,
            dataType: this.props.match.params.type,
            AllLibraryId: this.props.match.params.type === 2 ? true : false,
        }, async () => {
            this.getAllStores()
            // this.getOutPutList()
            let res = await this.getStores()
            if (!res.data || res.data.length === 0) {
                store.dispatch({
                    type: 'SavePageTabValue',
                    data: {
                        tab: 'store'
                    }
                })
                Modal.warning({
                    title: '提示',
                    content: '尚未创建仓库，是否立即添加仓库？',
                    okText: '去添加',
                    onOk: () => {
                        this.props.history.push('/storageManager/store')
                    }
                });
                return
            }

            if (this.state.id !== 'null') {
                this.getView()
            } else {
                this.FormRef.current.setFieldsValue({
                    libraryId: this.state.storeList[0].id,
                    dataType: this.props.match.params.type
                })
            }

        })
    }
    del(row, index) {
        React.$confirm({
            title: "提示",
            type: 'warning',
            content: "确定是否删除？",
            onOk: async () => {
                let res = await apiStockOutLibraryInfoDel({
                    id: row.id,
                    dataType: row.dataType,
                    goodsSkuId: row.goodsSkuId,
                    count: row.count
                })
                if (res.code === 0) {
                    let dataSource = this.state.dataSource
                    dataSource.splice(index, 1)
                    this.setState({
                        searchDataSource: []
                    }, () => {
                        this.setState({
                            searchDataSource: dataSource
                        })
                    })
                    React.$message({
                        type: 'success',
                        content: res.codeMessage
                    })
                } else {
                    React.$message({
                        type: 'warning',
                        content: res.codeMessage
                    })
                }



            }
        });

    }
    // 获取出入类型
    // async getOutPutList(){
    //     let firstTypeId = this.props.location.search.split('=')[1]
    //     if(firstTypeId == null){
    //         this.setState({
    //             options: [
    //                 { name: '商城销售出库单', value: '0', disabled: true },
    //             { name: '门店销售出库单', value: '1', disabled: true },
    //             { name: '调拨出库单', value: '2', disabled: false },
    //             { name: '手动创建出库单', value: '3', disabled: false },
    //             { name: '发起砍价', value: '4', disabled: true },
    //             { name: '收银台出库单', value: '5', disabled: true }
    //             ],
    //         })
    //     }else{
    //         let res = await apiTSysDictionariesList({pid: firstTypeId})
    //     this.setState({
    //         options: res.data,
    //     })
    //     }

    // }
    async getView() {
        let res = await apiStockOutLibraryView({ id: this.state.id })
        if (res.code === 0) {
            await this.getGoodsList(res.data.libraryId)
            this.setState({
                isSave: true,
                details: res.data,
                dataSource: this.state.dataSource.concat(res.data.infoList),
                code: res.data.code,
                outLibraryId: res.data.id,
                libraryId: res.data.libraryId,
                status: res.data.status,
                searchDataSource: this.state.dataSource.concat(res.data.infoList),
                AllLibraryId: this.props.match.params.type === '2' ? true : false,
            })
            this.FormRef.current.setFieldsValue({
                libraryId: res.data.libraryId,
                dataType: this.props.match.params.type,
                remark: res.data.remark ? res.data.remark : ' ',
                dataId: res.data.dataId,
            })
            if (res.data.status === 1 || [0, 1, 4, 5].includes(res.data.dataType)) {
                let columns = this.state.columns
                columns.pop()
                this.setState({
                    columns: []
                }, () => {
                    this.setState({
                        columns: columns
                    })
                })
            }
            // 已提交状态显示金额列
            if (res.data.status === 1 && [0, 1, 4, 5].includes(res.data.dataType)) {
                let columns = this.state.columns
                columns.splice(4, 0,
                    {
                        title: "金额",
                        dataIndex: "unitPrice",
                        key: "unitPrice",
                        render: (text, record) => {
                            return record.unitPrice >= 0 ? ((record.unitPrice) / 100).toFixed(2) : "-"
                        }
                    }
                )
                this.setState({
                    columns: []
                }, () => {
                    this.setState({
                        columns: columns
                    })
                })
            }
        }
    }
    async getGoodsList(libraryId) {
        let res = await apiGetGoodsList({ libraryId, type: 1 })
        if (res.code === 0) {
            this.setState({
                goodsList: res.data,
            })
        }
    }
    selectFilter(input, option) {
        const materialIds = option.option.materialIds.toLowerCase().split(',')
        const result = option.children.toLowerCase().includes(input.toLowerCase()) || materialIds.includes(input.toLowerCase())
        return result
    }
    goodsChange(e, row) {
        this.apiGetGoodsDetail(e)
    }
    async apiGetGoodsDetail(goodsId, skuId) {
        let res = await apiGetGoodsDetail({ goodsId, libraryId: this.state.libraryId })
        if (res.code === 0) {
            if (this.state.materialId) {
                let result = res.data.skuInfo.filter(item => item.materialId === this.state.materialId)
                this.setState({
                    productSku: res.data,
                    currentSku: result.length > 0 ? result[0] : res.data.skuInfo[0]
                })
            } else {
                this.setState({
                    productSku: res.data,
                    currentSku: res.data.skuInfo[0]
                })
            }

        }
    }
    // 获取供应商list
    async getSuppliers() {
        let res = await apiStockSupplierManageList()
        if (res.code === 0) {

            this.setState({
                supplierList: res.data
            })
        }
    }
    // 获取仓库list
    async getStores() {
        let res = await apiStockLibraryManageList()
        if (res.code === 0) {

            this.setState({
                storeList: res.data
            })
        }
        return res
    }
    async getAllStores() {
        let res = await apiStockLibraryManageList({ dataId: -1 })
        if (res.code === 0) {

            this.setState({
                allStoreList: res.data
            })
        }
        return res
    }
    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo, pageSize
            }
        }, () => {
            this.getData()
        })
    };
    triggerSkuTag(row) {

        this.setState({
            currentSku: row
        })
    }
    async onFinishAdd(values) {
        let { outLibraryId, currentSku, productSku, code } = this.state
        if (currentSku.libraryGoodsId == 0) {
            React.$message({
                type: 'warning',
                content: '当前商品尚未入库，请出库后执行此操作！'
            })
            return
        }
        let res = await apiStockOutLibraryInfoAdd({
            outLibraryId: outLibraryId,
            goodsId: values.goodsId,
            goodsSkuId: currentSku.SKUId,//skuId
            libraryGoodsId: currentSku.libraryGoodsId,//
            code: code,
            count: values.nowCount,//盘点库存
            beforeCount: currentSku.stock,//当前库存
            goodsName: productSku.goodsInfo.goodsName
        })
        if (res.code === 0) {
            message.success(res.codeMessage);
            this.reset()
            this.setState({
                dataSource: this.state.dataSource.concat(res.data),
                searchDataSource: this.state.dataSource.concat(res.data),
                isModalVisible: false
            })

        }
    }
    onFinishSearch() { }

    handleCancel() { }
    saveOutPutOrder = () => {
        Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined />,
            content: '保存出库单后将不可修改，确定保存出库单吗？',
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                let values = this.FormRef.current.getFieldsValue()
                let res = await apiStockOutLibraryAdd({
                    libraryId: values.libraryId,
                    dataType: values.dataType,
                    remark: values.remark ? values.remark : '',
                    dataId: values.dataId ? values.dataId : ""
                })
                if (res.code === 0) {
                    this.getGoodsList(values.libraryId)
                    this.setState({
                        isSave: true,
                        code: res.data.code,
                        outLibraryId: res.data.id,
                        libraryId: values.libraryId,
                        dataId: res.data.dataId,
                    })
                }

            }
        });
    }
    reset() {
        this.addFormRef.current.setFieldsValue({
            nowCount: null,
            goodsId: '',
            dataType: ''
        })
        this.setState({
            productSku: {},
            currentSku: {}
        })
    }
    execute() {
        React.$confirm({
            title: "提示",
            type: 'warning',
            content: "是否确定操作？",
            onOk: async () => {
                let res = await apiStockOutLibraryConfirm({
                    "id": this.state.outLibraryId,
                })
                if (res.code === 0) {
                    React.$message({
                        type: 'success',
                        content: res.codeMessage
                    })
                    setTimeout(() => {
                        this.props.history.go(-1)
                    }, 2000);
                }
            }
        })

    }
    exportGoodsDetail() {
        const th_arr = [
            {
                title: `出库单详情(单号：${this.state.code})`,
                prop: '',
                children: [
                    {
                        title: '商品名称',
                        prop: 'goodsName',
                    },

                    {
                        title: '物料名称',
                        prop: 'materialName',
                    },
                    {
                        title: '规格',
                        prop: 'skuName',
                    },
                    {
                        title: "物料ID",
                        prop: "goodsSkuNo",
                    },
                    {
                        title: '出库前库存',
                        prop: 'beforeCount',
                        valueType:'number'
                    },
                    {
                        title: '入库数量',
                        prop: 'count',
                        valueType:'number'
                    },
                    {
                        title: '操作时间',
                        prop: 'createTime',
                    },
                    {
                        title: '操作人',
                        prop: 'createUserName',
                    }

                ]
            },

        ]
        let tb_arr = this.state.dataSource
        exportSheetTable({ fileName: `出库单详情(单号：${this.state.code})`, tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: false, })
    }
    onBlur = (materialId) => {
        this.setState({
            materialId
        })
    }
    OptionChange = (value) => {
        value === "2" ?
            this.setState({
                AllLibraryId: true
            }) :
            this.setState({
                AllLibraryId: false
            })

    }
    setSearchValue = (value) => {
        const { dataSource } = this.state
        let search = value.target.value.trim()
        if (search) {
            this.setState({
                searchDataSource: this.getSearchData(dataSource, search)
            })
        } else {
            this.setState({
                searchDataSource: this.state.dataSource
            })
        }
    }
    getSearchData(aim, searchVal) {
        let newArr = []
        for (var i = 0; i < aim.length; i++) {
            let value = aim[i].goodsName, value1 = aim[i].goodsSkuNo, value2 = aim[i].materialName
            if (value.includes(searchVal) || value1.includes(searchVal) ||value2.includes(searchVal) ) {
                newArr.push(aim[i]);//将值放入第二个数组
            }
        }
        return newArr
        // return aim.filter(item => item.goodsName == goodsName)
    }
    //打印
    billPrint = async () => {
        const res = await apiStockOutLibraryPrintDetail({ id: this.state.id })
        if (res.code === 0) {
            toPrint(res.data)
        }
    }
    render() {
        let { columns, supplierList, searchDataSource, status, goodsList, outLibraryId, details, options, storeList, productSku, currentSku, dataSource, pageData, total, isModalVisible, loading, isSave, AllLibraryId, allStoreList } = this.state
        return (
            <div className="p-layout-box">
                <GoBack history={this.props.history} title="新增出库管理" />
                <Form layout={'inline'} ref={this.FormRef} onFinish={this.onFinishSearch} style={{ marginBottom: 12, marginTop: 12 }}>
                    <Form.Item name={"libraryId"}>
                        <Select disabled={outLibraryId} style={{ width: 200 }} placeholder={"出库仓库"}>
                            {
                                storeList.map(item => {
                                    return <Option value={item.id}>{item.name}</Option>
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="dataType"
                    >
                        <Select disabled={outLibraryId} style={{ width: 200 }} placeholder={"出库类型"} onChange={(e) => this.OptionChange(e)}>
                            {
                                options.map(item => {
                                    return <Option disabled={item.disabled} value={item.value}>{item.name}</Option>
                                })
                            }
                        </Select>
                    </Form.Item>
                    {AllLibraryId &&
                        <Form.Item name={"dataId"}>
                            <Select disabled={outLibraryId} style={{ width: 200 }} placeholder={"调拨仓库"}>
                                {
                                    allStoreList.map(item => {
                                        return <Option value={item.id}>{item.name}</Option>
                                    })
                                }
                            </Select>
                        </Form.Item>
                    }
                    <Form.Item name={"remark"}>
                        <TextArea disabled={outLibraryId} autoSize={false} rows={1} style={{ width: 340 }} maxLength={300} placeholder={"备注"} />
                    </Form.Item>
                    <Space direction="vertical">
                        <Search
                            placeholder="请输入物料名称/物料ID"
                            onChange={(e) => this.setSearchValue(e)}
                            style={{
                                width: 200,
                            }}
                            allowClear
                        />
                    </Space>
                    <Space style={{ marginLeft: 12 }}>
                        <TheButton onClick={() => this.exportGoodsDetail()} haspermi={['storage:outPut:exportGoodsDetail']} size="middle" type="default">导出</TheButton>
                        {/* {
                            details.finishTime == null ? null : <TheButton haspermi={['storage:outPut:print']} onClick={this.billPrint} size="middle" type="default">打印</TheButton>
                        } */}
                    </Space>
                </Form>
                {
                    status !== 1 && ![0, 1, 4, 5].includes(details.dataType) ? <div style={{ marginBottom: 12 }}>
                        {
                            !isSave ?
                                <TheButton onClick={() => this.saveOutPutOrder()} haspermi={['storage:outPut:saveOutPutOrder']} size="middle" type="primary">保存出库单</TheButton>
                                :
                                <div>
                                    {/* <TheButton style={{ marginRight: 8 }} haspermi={['storage:putIn:upload']} size="middle" type="default">导入</TheButton>
                                <TheButton style={{ marginRight: 8 }} haspermi={['storage:putIn:downLoad']} size="middle" type="default">导出</TheButton> */}
                                    <TheButton onClick={() => this.setState({ isModalVisible: true })} haspermi={['storage:outPut:addInfo']} size="middle" type="primary">添加商品</TheButton>
                                </div>
                        }
                    </div> : null
                }

                <TheTable
                    scroll={{ x: "max-content", y: '63vh' }}
                    columns={columns}
                    dataSource={searchDataSource}
                />
                {
                    status !== 1 && ![0, 1, 4, 5].includes(details.dataType) ? <div style={{ textAlign: 'center', marginTop: 12 }}>
                        {
                            dataSource.length > 0 &&
                            <TheButton type="primary" haspermi={['storage:outPut:execute']} size='middle' onClick={() => this.execute(1)}>提交</TheButton>

                        }
                    </div> : null
                }
                <Modal title="新增" visible={isModalVisible} width="40%"

                    onCancel={() => this.setState({ isModalVisible: false })}
                    footer={null}
                >
                    <Form
                        labelCol={{
                            span: 4,
                        }}
                        wrapperCol={{
                            span: 16,
                        }}
                        ref={this.addFormRef}
                        onFinish={(values) => this.onFinishAdd(values)}
                    >
                        <Row>

                            <Col span={24}>
                                <Form.Item

                                    label="选择商品"
                                    name="goodsId"
                                    rules={[
                                        {
                                            required: true,
                                            message: '请选择商品!',
                                        },
                                    ]}
                                >
                                    <Select

                                        showSearch
                                        optionFilterProp="children"
                                        filterOption={(input, option) => this.selectFilter(input, option)}
                                        style={{
                                            width: '100%',
                                        }}
                                        onSearch={(e) => this.onBlur(e)}
                                        onSelect={(e, obj) => this.goodsChange(e, obj)}
                                        placeholder="请选择商品"
                                    >
                                        {
                                            goodsList.map(item => <Option option={item} key={item.goodsId} value={item.goodsId}>{item.goodsName}</Option>)
                                        }
                                    </Select>

                                </Form.Item >
                            </Col>

                            <Col>
                                {
                                    productSku.hasOwnProperty('goodsInfo') ?
                                        <Form.Item
                                            wrapperCol={{
                                                offset: 4,
                                                span: 16,
                                            }}
                                        >
                                            <div className='goodsDesc'>
                                                <div className='info'>
                                                    <img src={currentSku.imageFile ? currentSku.imageFile.split(',')[0] : ''} alt="商品图片" className='goodsImg' />
                                                    <div className="goodsInfo">
                                                        <div className='name'>{productSku.goodsInfo.goodsName}</div>
                                                        <div className='stock' >
                                                            物料ID：{currentSku.materialId}
                                                        </div>
                                                        <div className='stock' >
                                                            物料名称：{currentSku.materialName}
                                                        </div>
                                                        <div className='stock' >
                                                            可售库存：{currentSku.stock}
                                                        </div>
                                                        <div className='stock' >
                                                            待出库存：{currentSku.waiteOutCount}
                                                        </div>
                                                        <div className='stock' >
                                                            实际库存：{currentSku.realStock}
                                                        </div>
                                                    </div>
                                                </div>
                                                <div className='goodsSku'>
                                                    {
                                                        productSku.skuInfo.map(item =>
                                                            <Tag className='tag' key={item.SKUId} color={item.SKUId === currentSku.SKUId ? "cyan" : ''} onClick={() => this.triggerSkuTag(item)}>
                                                                {item.skuAttribute.map(item2 => item2.value).join(',')}
                                                            </Tag>
                                                        )
                                                    }

                                                </div>
                                            </div>
                                        </Form.Item> : null
                                }
                            </Col>


                            <Col span={24}>
                                <Form.Item
                                    label="出库数"
                                    name="nowCount"
                                    rules={[
                                        {
                                            required: true,
                                            message: '请输入!',
                                        },
                                    ]}
                                >
                                    <InputNumber style={{
                                    }} precision={0} min={0} />
                                </Form.Item>
                            </Col>
                            <Col>
                                <Form.Item wrapperCol={{
                                    offset: 8,
                                    span: 16,
                                }}>
                                    <Space size="small" style={{ marginLeft: 10 }}>

                                        <Button type="default" onClick={() => this.reset()}>
                                            重置
                                        </Button>
                                        <Button type="primary" htmlType="submit">
                                            确定
                                        </Button>
                                    </Space>
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>
                </Modal>
            </div>
        );
    }
}
